package org.phalanx.gwt.client.shared;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

public class ServerMessage {
	public static final String IS_GET = "get";
	public static final String IS_POST = "post";
	private String context;
	private HashMap<String, String> messageContents;
	private boolean isGET = true;
	
	public ServerMessage(){
		initializeMessageStore();
	}
	
	public ServerMessage(String context){
		this.setContext(context);
		initializeMessageStore();
	}
	
	public void setGET(){
		isGET = true;
	}
	
	public void setPOST(){
		isGET = false;
	}
	
	public String getMessageTransport(){
		return isGET ? IS_GET : IS_POST;
	}
	
	private void initializeMessageStore(){
		messageContents = new HashMap<String,String>();
	}
	
	public void setContext(String context){
		this.context = context;
	}
	
	public String getContext(){
		return context;
	}
	
	public void addMessageContents(String key, String value){
		messageContents.put(key, value);
	}
	
	public void removeMessageContents(String key){
		if (messageContents.containsKey(key)){
			messageContents.remove(key);
		}
	}
	
	public void clearMessageContents(){
		if (messageContents.isEmpty()){
			messageContents.clear();
		}
	}
	
	public String getMessageContentsValue(String key){
		return messageContents.get(key);
	}
	
	public ArrayList<String> getMessageKeys(){
		ArrayList<String> keyStore = new ArrayList<String>();
		keyStore.addAll(messageContents.keySet());
		return keyStore;
	}
	
	private void applyTimeStamp(){
		String dateTimeStamp = new Date().getTime() + "";
		this.addMessageContents("timestamp", dateTimeStamp);
	}
	
	public String generateMessageBody(){
		StringBuffer msgBody = new StringBuffer();
		
		if (context != null){
			msgBody.append("context");
			msgBody.append("=");
			msgBody.append(context);
			
			ArrayList<String> keySet = getMessageKeys();
			
			for (int i = 0; i < keySet.size(); i++){
				msgBody.append("&");
				String tempKey = keySet.get(i);
				msgBody.append(tempKey);
				msgBody.append("=");
				msgBody.append(this.getMessageContentsValue(tempKey));
			}
		}
		
		return msgBody.toString();
	}
}
